<template>
    <div class="notice-container">
      <el-card class="animated-card">
        <!--操作区域 start-->
         <!-- 新增查询和操作区域 -->
      <div class="filter-container">
        <el-row :gutter="15">
          <el-col :span="6">
            <el-input
              v-model="searchTitle"
              placeholder="请输入公告标题"
              clearable
              @keyup.enter="loadData"
            />
          </el-col>
          <el-col :span="4">
            <el-button
              type="primary"
              @click="loadData"
              class="search-btn"
            >
              查询
            </el-button>
          </el-col>
          <el-col :span="14" class="text-right">
            <el-button
              type="success"
              @click="handleCreate"
              class="add-btn"
            >
              新增公告
            </el-button>
            <el-button
              type="danger"
              @click="handleBatchDelete"
              :disabled="selectedIds.length === 0"
            >
              批量删除
            </el-button>
          </el-col>
        </el-row>
      </div>
        <!-- 操作区域 end -->
        <el-table
          :data="noticeList"
          style="width: 100%"
          :row-class-name="tableRowClassName"
          @selection-change="handleSelectionChange"
          v-loading="loading"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column prop="title" label="公告标题" />
          <el-table-column prop="realName" label="创建人" width="150" />
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" width="220">
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                @click="handleView(scope.row)"
                class="action-btn"
              >
                查看
              </el-button>
              <el-button
                type="warning"
                size="small"
                @click="handleEdit(scope.row)"
                class="action-btn"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(scope.row.id)"
                class="action-btn"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
         <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="fetchData"
        @current-change="fetchData"
      />
    </div>
      </el-card>
  
      <notice-drawer
        v-model="drawerVisible"
        :form-data="currentNotice"
        :is-edit="isEditMode"
        @submit="handleSubmit"
      />
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, reactive,onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import NoticeDrawer from './NoticeDrawer.vue'
  import { noticePagingApi,addOrUpdateNoticeApi,
     deleteNoticeApi,deleteBatchNoticeApi } from '@/api/notices';
  
  interface Notice {
    id: number
    title: string
    content: string
    realName: string
    createTime: string
  }

  const selectedIds = ref<number[]>([]); // 存储选中ID

  // 选中处理
const handleSelectionChange = (selection: Notice[]) => {
  selectedIds.value = selection.map(item => item.id);
};

  const currentPage = ref(1)
  const pageSize = ref(10)
  const total = ref(0)
  
  const loading = ref(false)
  const drawerVisible = ref(false)
  const isEditMode = ref(false)
  const currentNotice = ref<Partial<Notice>>({})
  
  const noticeList = ref<Notice[]>([])

  // 新增查询条件
const searchTitle = ref('')

// 新增按钮处理
const handleCreate = () => {
  isEditMode.value = true
  currentNotice.value = {
    title: '',
    content: '',
    creator: '',
    createTime: ''
  }
  drawerVisible.value = true
}
  
  const handleView = (row: Notice) => {
    isEditMode.value = false
    currentNotice.value = { ...row }
    drawerVisible.value = true
  }
  
  const handleEdit = (row: Notice) => {
    isEditMode.value = true
    currentNotice.value = { ...row }
    drawerVisible.value = true
  }
  
  // 删除单条记录
  const handleDelete = async(id: number) => {
    ElMessageBox.confirm('确定要删除该公告吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async() => {
      // 删除逻辑
     const {code,msg} =  await deleteNoticeApi(id)
     if (code===1) {
      ElMessage.success(msg)
      loadData()
     } else {
      ElMessage.error(msg)
     }
      
    })
  }

  // 批量删除
  const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) return;
  
  ElMessageBox.confirm('确定删除选中公告？', '警告', {
  }).then(async () => {
    const idsStr = selectedIds.value.join(',');
    const { code, msg } = await deleteBatchNoticeApi(idsStr);
    
    if (code === 1) {
      ElMessage.success(msg);
      selectedIds.value = []; // 清空选中
      loadData();
    }

  });
};
  
  /**
   * 提交处理逻辑
   * @param formData 
   */
  const handleSubmit = async(formData: Notice) => {
    try {
      const postData = {
              "id": formData.id,
              "title": formData.title,
              "content": formData.content
            }
      const {code,msg} = await addOrUpdateNoticeApi(postData)
      if(code === 1){
        ElMessage.success(msg)
        drawerVisible.value = false
        loadData()
      }else{
        ElMessage.error(msg)
      }

    } catch (error) {
      console.log('提交失败', error)
    }
    
  
}
  
  const tableRowClassName = () => {
    return 'table-row'
  }

  /**
   * 加载数据
   */
  const loadData = async() => {

    try {
      // 查询参数
      const params = {
        pageNum: 1,
        pageSize: 10,
        title: searchTitle.value // 添加标题查询参数
      }
      const { data } = await noticePagingApi(params)
      noticeList.value = data.records
      total.value = data.total
      console.log(data)
    } catch (error) {
      
    }
  }

  // 初始化数据
  onMounted(() => {
    loadData()
  })
  </script>
  
  <style lang="scss" scoped>
  .notice-container {
    padding: 20px;
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    min-height: 100vh;

    .pagination {
      display: flex;
      margin-top: 20px;
      justify-content: center;
    }

    .filter-container {
    margin-bottom: 20px;

    .text-right {
      text-align: right;
    }

    .search-btn {
      margin-left: 10px;
    }

    .add-btn {
      margin-right: 10px;
    }
  }
  
    .animated-card {
      transition: all 0.3s ease;
      &:hover {
        transform: translateY(-3px);
        box-shadow: 0 10px 20px rgba(64, 158, 255, 0.2);
      }
    }
  
    .action-btn {
      transition: all 0.2s ease;
      &:hover {
        transform: scale(1.05);
      }
    }
  
    :deep(.table-row) {
      transition: background-color 0.3s ease;
      &:hover {
        background-color: rgba(64, 158, 255, 0.1) !important;
      }
    }
  
    :deep(.el-table) {
      --el-table-header-bg-color: #{rgba(64, 158, 255, 0.08)};
      --el-table-border-color: #{rgba(64, 158, 255, 0.1)};
    }
  }
  </style>